<?php
/**
 * Created by PhpStorm.
 * User: yu
 * Date: 16-11-15
 * Time: 上午11:21
 */

namespace message\service;

use herosphp\core\Loader;
use herosphp\bean\Beans;
use utils\sms\ProviderFactory;
use herosphp\core\Log;

Loader::import('utils.x1.MyFunction');
Loader::import('utils.sms.ProviderFactory');

class SmsService
{

    const PROVIDER_YUNPIAN = 'YunPian';
    const PROVIDER_SMSBAO = 'SmsBao';
    const PROVIDER_CHUANGLAN = 'ChuangLan';
    const PROVIDER_CR6868 = 'Cr6868';

    //获取默认短信服务商信息
    public function getDefaultProvider()
    {
        $settingService = Beans::get('admin.adminSetting.service');
        $arr = $settingService->getSmsConfig();

        $arr = array(
            'name' => $arr['sms_provider'],
            'info' => array(
                'user' => $arr['sms_account'],
                'pass' => $arr['sms_password'],
                'key' => $arr['sms_key'],
                'sign' => $arr['sms_sign'],
            )
        );

        return $arr;
    }

    /**
     * 发送短信
     * @param $mobile 手机号
     * @param $content 短信内容
     * @return bool
     */
    public function send($mobile, $content)
    {
        $providerConfig = $this->getDefaultProvider();

        if (!in_array($providerConfig['name'], array(
            self::PROVIDER_YUNPIAN,
            self::PROVIDER_SMSBAO,
            self::PROVIDER_CHUANGLAN, self::PROVIDER_CR6868))
        ) {

            Log::info("发送短信:运营商未命中");

            return false;
        }
        if (C('sms_open') == 'off') {

            Log::info("短信服务已在网站设置中被禁用");

            return false;
        }
        $provider = ProviderFactory::getProvider($providerConfig['name']);
        $provider->auth($providerConfig['info']['user'], $providerConfig['info']['pass'], '', $providerConfig['info']['sign']);
        $result = $provider->send($mobile, $content);
        return $result;

    }

    /**
     * 直接发送，不用配置信息
     * @param $mobile
     * @param $content
     * @param $providerName
     * @param $user
     * @param $pass
     * @param $sign
     * @return bool|mixed
     */
    public function directSend($mobile, $content, $providerName, $user, $pass, $sign)
    {


        if (!in_array($providerName, array(
            Self::PROVIDER_YUNPIAN,
            Self::PROVIDER_SMSBAO,
            Self::PROVIDER_CHUANGLAN, Self::PROVIDER_CR6868))
        ) {

            Log::info("发送短信:运营商未命中");

            return false;
        }
        if (C('sms_open') == 'off') {

            Log::info("短信服务已在网站设置中被禁用");

            return false;
        }
        $provider = ProviderFactory::getProvider($providerName);
        $provider->auth($user, $pass, '', $sign);
        $result = $provider->send($mobile, $content);
        return $result;

    }


}